/**
 * 
 */
package com.res.simulator.handler;

import java.text.DateFormat;
import java.util.Date;

import com.res.common.handler.CommonHandler;
import com.res.simulator.model.StoreFrontEligibilityModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.view.StoreFrontView;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.comserver.communication.utils.CommonUtils;

/**
 * @author Dhanushka Ariyasingha
 * 
 */
public class StoreFrontHandler implements
		CommonHandler<StoreFrontView, StoreFrontEligibilityModel> {

	public StoreFrontView process(final StoreFrontEligibilityModel model)
			throws Exception {
		// TODO Auto-generated method stub

		final CommunicationMessage message = extract(model);

		final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
		final CommunicationMessage returnedMessage = plugin.invoke(message);

		System.out.println("Recieced message :"	+ returnedMessage.getMessageBody());

		final String fileName = generateFileName(returnedMessage.getMessageBody());
		final CommonFileHandler fileHandler =new CommonFileHandler();
		
		final String fileUrl = fileHandler.save((String) returnedMessage.getObject(),
				fileName);

		final StoreFrontView view = new StoreFrontView();

		view.appendLocation(fileName, fileUrl);

		return view;
	}

	private CommunicationMessage extract(final StoreFrontEligibilityModel model) {

		final CommunicationMessage message = new CommunicationMessage();
		//CHANNEL:CSSC|
		final String channel = model.getStorefront();

		String eligibleString = model.getEligibleString();
		eligibleString = eligibleString.concat(eligibleString + "|SIM_CHANNEL:" + channel);

		message.setMessageHeader("JOBType:StoreFront|ID:dev44.aepona.com");

		message.setMessageBody(eligibleString);

		System.out.println("Print Pass message body .. " + message.getMessageBody());

		return message;

	}

	private String generateFileName(final String valueString) throws Exception {

		final Date now = new Date();
		final String dateTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now);

		final String channel = CommonUtils.find(valueString, "SIM_CHANNEL");

		final String fileName = channel + "-" + now.getTime() + ".xml";

		return fileName;
	}

}
